import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    children:[
      // 桌面
      { path: '/desktop', component: () => import('../components/Desktop') },
      // 视频管理
      { path: '/course', component: () => import('../components/Course') },
      // 成员管理
      { path: '/user', component: () => import('../components/User') },
      // 学习记录
      { path: '/user/learn/:id', component: () => import('../components/Learn') },
      // 志愿者审核
      { path: '/user-audit', component: () => import('../components/User-audit') },
      // 志愿者审核
      { path: '/manager', component: () => import('../components/Manager') },
      // 系统公告
      { path: '/notice', component: () => import('../components/Notice') },
      // 访问统计
      { path: '/visit', component: () => import('../components/Visit') },
      // 系统设置
      { path: '/setting', component: () => import('../components/Setting') },
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  }
]

const router = new VueRouter({
  routes
})


router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  //  from 从哪个路径跳转过来的
  //  next 他是函数代表放行
  const myToken = sessionStorage.getItem('token')
  if (to.path === '/login') {
    if (myToken) return next('/home')
    next()
  } else {
    if (!myToken) return next('/login')
    if (to.path === '/login') return next('/home')
    next()
    // 登录状态
  }
})

export default router

// vue重复点击路由 导致冗余导航的解决方法
const routerRePush = VueRouter.prototype.push
VueRouter.prototype.push = function (location) {
  return routerRePush.call(this, location).catch(error => error)
}
